package com.vision.core.cl.ui.component;

import java.util.List;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.uibinder.client.UiConstructor;
import com.sencha.gxt.data.shared.LabelProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.widget.core.client.form.ComboBox;
import com.vision.core.cl.Callback;
import com.vision.core.cl.ui.UI;
import com.vision.core.cm.data.CompanyProperties;
import com.vision.core.cm.db.data.Company;
import com.vision.core.cm.serv.rpc.CompanyServiceAsync;

/**
 * 
 * @author Mark
 *
 */
public class CompanyComboBox extends ComboBox<Company> {

	@UiConstructor
	public CompanyComboBox() {
		this(new ListStore<Company>(CompanyProperties.INSTANCE.key()));
	}

	private CompanyComboBox(ListStore<Company> store) {
		super(store, new LabelProvider<Company>() {
			@Override
			public String getLabel(Company company) {
				return company.getCode();
			}
		});
	}
	
	public void loadCompanies() {
		UI.mask(this, "Loading company data...");
		CompanyServiceAsync.INSTANCE.getAll(new Callback<List<Company>>(this) {
			@Override
			protected void handleSuccess(List<Company> result) {
				getStore().clear();
				getStore().addAll(result);
				
				if (getStore().size() == 1) {
					Scheduler.get().scheduleDeferred(new ScheduledCommand() {
						@Override
						public void execute() {
							select(0);
						}
					});
				}
			}
		});
	}

}
